package net.liteheaven.xblib.common.xadapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * BaseAdapter的封装
 * 封装方式参考RecyclerView
 *
 * Created by liangy on 2016/12/26.
 */
public abstract class XAdapter<D, H extends XHolder> extends BaseAdapter {

    protected List<D> dataList = new ArrayList<>();
    private IXAdapterBehavior<D, H> capacity;

    public XAdapter(){
    }

    abstract protected IXAdapterBehavior<D, H> onCreateCapacity();

    public void add(D data){
        this.dataList.add(data);
        notifyDataSetChanged();
    }

    public void update(List<D> dataList){
        this.dataList = dataList;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public D getItem(int position) {
        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (capacity == null){
            capacity = onCreateCapacity();
        }

        View v;
        if (convertView == null){
            H holder = capacity.onCreateViewHolder(parent, getItemViewType(position));
            v = holder.itemView;
            v.setTag(holder);
        }else{
            v = convertView;
        }
        D item = getItem(position);
        capacity.onBindViewHolder(item, (H)v.getTag());
        return v;
    }
}
